<template>
    <el-form ref="formRef" :model="form" label-width="120px">
      <!-- 其他表单字段 -->
      <el-form-item label="文件上传">
        <el-upload
          :action="uploadAction"
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          :limit="1"
          ref="uploadRef"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitForm">上传到服务器</el-button>
        </el-upload>
      </el-form-item>
      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交表单</el-button>
      </el-form-item>
    </el-form>
  </template>
  
  <script>
  import { ref } from 'vue';
  import axios from 'axios';
  
  export default {
    setup() {
      const formRef = ref(null);
      const uploadRef = ref(null);
      const fileList = ref([]);
      const selectedFile = ref(null);
  
      const uploadAction = '';
  
      const handleFileChange = (file, fileList) => {
        // 存储选中的文件
        selectedFile.value = file.raw;
        fileList.value = fileList;

        console.log("select:",selectedFile.value,fileList.value)
      };
  
      const submitForm = async () => {
        // 表单验证
        await formRef.value.validate((valid) => {
          if (valid) {
            // 如果验证通过，上传文件
            uploadFile();
          } else {
            console.log('表单验证失败');
            return false;
          }
        });
      };
  
      const uploadFile = () => {
        if (selectedFile.value) {
          const formData = new FormData();
          formData.append('file', selectedFile.value);
          // 可以在这里添加其他表单数据
          // formData.append('otherData', otherData);
  
          axios({
            method: 'post',
            url: uploadAction,
            data: formData,
            headers: { 'Content-Type': 'multipart/form-data' },
          })
          .then(response => {
            console.log('文件上传成功', response);
            // 清空文件列表和已选文件
            fileList.value = [];
            selectedFile.value = null;
          })
          .catch(error => {
            console.error('文件上传失败', error);
          });
        }
      };
  
      return {
        formRef,
        uploadRef,
        fileList,
        selectedFile,
        uploadAction,
        handleFileChange,
        submitForm,
        uploadFile,
      };
    },
  };
  </script>
  